import 'package:video_player/video_player.dart';

const _maxPlayCounter = 10;

class VideoControllerPool {
  static VideoControllerPool _instance;
  List<VideoPlayerController> controllerList = [];

  factory VideoControllerPool() => _instance ??= VideoControllerPool._();

  VideoControllerPool._();

  Future<VideoPlayerController> obtainController(String path) async {
    VideoPlayerController controller;

    if (path.startsWith('http')) {
      controller = VideoPlayerController.network(path);
    } else {
      controller = VideoPlayerController.asset(path);
    }
    controller.setLooping(true);
    controllerList.add(controller);
    if (controllerList.length > _maxPlayCounter) {
      final removeController = controllerList.removeAt(0);
      removeController.pause();
      await removeController.dispose();
    }
    controller.addListener(() {
      if (controller.value.isPlaying) {
        stopOtherPlay(controller.textureId);
      }
    });
    await controller.initialize();
    return controller;
  }

  void removeController(VideoPlayerController controller) {
    controller.dispose();
    controllerList.removeWhere((element) {
      return element.textureId == controller.textureId;
    });
  }

  void stopOtherPlay(int textureId) {
    controllerList.forEach((element) {
      if (element.value.isPlaying && element.textureId != textureId) {
        element.pause();
      }
    });
  }
}
